package vip.aster.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

/**
 * 查询Ip所在地理位置
 *
 * @author Aster
 * @since 2023/11/16 17:22
 */
@Slf4j
public class AddressUtils {
    /**
     * IP地址查询
     */
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    /**
     * 未知地址
     */
    public static final String UNKNOWN = "XX XX";

    /**
     * 10.x.x.x/8
     */
    private static final byte SECTION_1 = 0x0A;
    /**
     * 172.16.x.x/12
     */
    private static final byte SECTION_2 = (byte) 0xAC;
    private static final byte SECTION_3 = (byte) 0x10;
    private static final byte SECTION_4 = (byte) 0x1F;
    /**
     * 192.168.x.x/16
     */
    private static final byte SECTION_5 = (byte) 0xC0;
    private static final byte SECTION_6 = (byte) 0xA8;

    private static final String EXCEPTION_MESSAGE = "获取地理位置异常 {}";

    public static String getRealAddressByIp(String ip) {
        String url = IP_URL + "?ip=" + ip + "&json=true";
        String address = UNKNOWN;
        // 内网不查询
        if (internalIp(ip)) {
            return "内网IP";
        }
        try {
            String rspStr = HttpUtil.get(url, Charset.forName("GBK"));
            if (StrUtil.isBlank(rspStr)) {
                log.error(EXCEPTION_MESSAGE, ip);
                return UNKNOWN;
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            address = String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error(EXCEPTION_MESSAGE, e.getMessage());
        }

        return address;
    }

    /**
     * 判断是否内网ip
     *
     * @param ip
     */
    public static boolean internalIp(String ip) {
        byte[] addr = IpUtils.textToNumericFormatV4(ip);
        return internalIp(addr) || "127.0.0.1".equals(ip);
    }

    private static boolean internalIp(byte[] addr) {
        if (addr == null || addr.length < 2) {
            return true;
        }
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                return b1 == SECTION_6;
            default:
                return false;
        }
    }

    public static String getHostIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ignored) {
        }
        return "127.0.0.1";
    }

    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ignored) {
        }
        return "未知";
    }
}
